//
//  ToursimSecondVC.m
//  Buiom_7.0
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 triffe. All rights reserved.
//

#import "ToursimSecondVC.h"
#import "ToursimSecondModel.h"
#import "ToursimSecondCell.h"
#import "UIImageView+WebCache.h"
#import "ToursimThirdVC.h"
#import "MONActivityIndicatorView.h"

#define     KsWidth  [UIScreen mainScreen].bounds.size.width
#define     KsHeigh  [UIScreen mainScreen].bounds.size.height
@interface ToursimSecondVC ()<UITableViewDataSource, UITableViewDelegate,MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIAlertView *alter;
// 装数据的数组
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) MONActivityIndicatorView *indicationView;
// 声明一个上下拉刷新的索引属性
@property (nonatomic, assign) NSInteger pagesUpdata;


@end

@implementation ToursimSecondVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pagesUpdata = 0;
  //  self.view.backgroundColor = [UIColor greenColor];
    [self addSubView];
    
   // 加载一个动画加载等待
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.indicationView = [[MONActivityIndicatorView alloc] init];
    _indicationView.center = self.tableView.center;
    CGPoint point = _indicationView.center;
    point.y = self.tableView.center.y - 200;
    _indicationView.center = point;
    _indicationView.delegate = self;
    [self.tableView addSubview:_indicationView];
    [_indicationView startAnimating];
    // 加载刷新方法
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefering) dateKey:@"head"];
    [self.tableView addFooterWithTarget:self action:@selector(footerRefering)];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"刷新中。。。";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"加载中。。。";
    self.view.backgroundColor = [UIColor greenColor];
    
    
    // 加载数据
     [self addUpData];
    
    
}

// 上拉刷新
- (void)headerRefering
{
    // 刷新页数;
    self.pagesUpdata  += 20;
    // 重新加载数据
    [self addUpData];
    [self.tableView reloadData];
    
    // 加载完毕
    [self.tableView headerEndRefreshing];
}
// 下拉刷新
- (void)footerRefering
{
    // 刷新页数;
    self.pagesUpdata  += 20;
    
    NSString *urlString =[NSString stringWithFormat: @"http://api.breadtrip.com/destination/place/%@/%@/pois/all/?sort=default&start=%ld&sign=2b34502a63e3889ec8b70d962537d585", self.type, self.ID, self.pagesUpdata];
    NSLog(@"%@--%@", self.type, self.ID);
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 数据请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 进行数据解析
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        // 进行数据的解析
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic2 in array) {
            ToursimSecondModel *model = [[ToursimSecondModel alloc] init];
            
            model.visited_count = dic2[@"visited_count"];
            model.nextType = dic2[@"type"];
            model.name = dic2[@"name"];
            model.cover_s = dic2[@"cover_s"];
            model.recommended_reason = dic2[@"recommended_reason"];
            model.nextID = dic2[@"id"];
            
            [self.dataArray addObject:model];
            
            
        }
        
        [self.tableView reloadData];
        
    }];

    
    
    
    
    [self.tableView footerEndRefreshing];
}
// 添加加载圆圈动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    if (index == 0) {
        return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
    } if (index == 1) {
        return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
    } if (index == 2) {
        return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
    } if (index == 3) {
        return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
    }
    
    return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
}


// 加载视图
- (void)addSubView
{
self.navigationItem.title = @"旅游城市";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KsWidth, KsHeigh - 64) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    [self.view addSubview:_tableView];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"国家" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeft:)];
    self.navigationItem.leftBarButtonItem = left;
    
    // 添加一个图标,点击之后,可以实现返回到顶端的功能
    UIImageView *imageGoBack = [[UIImageView alloc] initWithFrame:CGRectMake(KsWidth - 50, KsHeigh - 50, 50, 50)];
    imageGoBack.image = [UIImage imageNamed:@"goback"];
    imageGoBack.userInteractionEnabled = YES;
    UITapGestureRecognizer *gobackGuest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goBackTopAction)];
    [imageGoBack addGestureRecognizer:gobackGuest];
    [self.view addSubview:imageGoBack];
    
}
// 点击图片返回顶部的方法
- (void)goBackTopAction
{
//    if (self.tableView.bounds.size.height == 603) {
//        self.alter = [[UIAlertView alloc] initWithTitle:@"小提示" message:@"亲,您已经在顶端了" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [_alter show];
//        [self performSelector:@selector(alterAction) withObject:_alter afterDelay:3.0];
//        
//    } else {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
   // }
}
- (void)alterAction
{
    [self.alter dismissWithClickedButtonIndex:0 animated:NO];
}



- (void)actionLeft:(UIBarButtonItem *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 每个分区有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataArray];
    return array.count;
}
// 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"sdffdfsa";
    ToursimSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ToursimSecondCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    // 进行赋值
    
    ToursimSecondModel *model = self.dataArray[indexPath.row];
    NSString *string = model.cover_s;
    NSURL *url = [NSURL URLWithString:string];
    [cell.imageViews sd_setImageWithURL:url];
    cell.titleLabel.text = model.name;
    
    
    if ([model.recommended_reason isEqual:[NSNull null]]) {
        
        cell.descriptionLsabel.text = @"暂无对此风景区的描述(敬请期待!)";
    } else if ([model.recommended_reason length] == 0) {
        cell.descriptionLsabel.text = @"暂无对此风景区的描述(敬请期待!)";
    }
    else {
        cell.descriptionLsabel.text = model.recommended_reason;
   }
  //  cell.countLabel.text =[NSString stringWithFormat:@"%@人已去过(⊙o⊙).", model.visited_count];
[_indicationView stopAnimating];
    return cell;
}
// 设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 190;
}
// cell的点击方法,跳转到下一个页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ToursimThirdVC *toursimthirdVC = [[ToursimThirdVC alloc] init];
    ToursimSecondModel *model = self.dataArray[indexPath.row];
    toursimthirdVC.types = model.nextType;
    toursimthirdVC.idds = model.nextID;
    toursimthirdVC.imageString = model.cover_s;
    // 跳转的同时传参数
    [self.navigationController pushViewController:toursimthirdVC animated:YES];
}

// 加载数据
- (void)addUpData
{
//    if (self.pagesUpdata == 0) {
//        
//    }
    
    [self.dataArray removeAllObjects];
    
    NSString *urlString =[NSString stringWithFormat: @"http://api.breadtrip.com/destination/place/%@/%@/pois/all/?sort=default&start=%ld&sign=2b34502a63e3889ec8b70d962537d585", self.type, self.ID, self.pagesUpdata];
    NSLog(@"%@--%@", self.type, self.ID);
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 数据请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 进行数据解析
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       
       // 进行数据的解析
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic2 in array) {
            ToursimSecondModel *model = [[ToursimSecondModel alloc] init];
            
            model.visited_count = dic2[@"visited_count"];
            model.nextType = dic2[@"type"];
            model.name = dic2[@"name"];
            model.cover_s = dic2[@"cover_s"];
            model.recommended_reason = dic2[@"recommended_reason"];
            model.nextID = dic2[@"id"];
            
            [self.dataArray addObject:model];
            
            
        }
        
        [self.tableView reloadData];
        
    }];
    
    
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
